package com.tim.servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.tim.pojo.DataResult;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

/**
 * 作者：Tim
 * 时间：2021/4/25 14:09
 */

public class BaseServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("application/json;charset=utf-8");
        //获取请求参数Method
        String methodName = req.getParameter("method");
        if(methodName == null || methodName == ""){
            DataResult dataResult = new DataResult(40000,"请求参数method错误");
            ObjectMapper mapper = new ObjectMapper();
            resp.getWriter().write(mapper.writeValueAsString(dataResult));
        }
        //反射调用
        Class c = this.getClass();   //由于底层代码原理，这个会调出子类的类对象
        try {
            Method method = c.getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            Object result = method.invoke(c.newInstance(), req, resp);
            if(result != null){
                ObjectMapper mapper = new ObjectMapper();
                resp.getWriter().write(mapper.writeValueAsString(result));
            }
        } catch (Exception e) {
            e.printStackTrace();
            DataResult dataResult = new DataResult(40000,"请求错误");
            ObjectMapper mapper = new ObjectMapper();
            resp.getWriter().write(mapper.writeValueAsString(dataResult));
        }


    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
